package cc.sjfx.sharedoc.widget.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;

import cn.bmob.v3.listener.UpdateListener;
import cn.mandroid.frame.toast.MLog;
import cn.mandroid.frame.toast.MToast;
import cn.mandroid.frame.utils.ThreadUtils;
import cc.sjfx.sharedoc.R;
import cc.sjfx.sharedoc.activity.BasicFragmentActivity;
import cc.sjfx.sharedoc.activity.examination.DetailActivity;
import cc.sjfx.sharedoc.activity.user.UserLoginActivity;
import cc.sjfx.sharedoc.bean.ExamShowListViewBean;
import cc.sjfx.sharedoc.cache.UserCache;
import cc.sjfx.sharedoc.db.UserDB;
import cc.sjfx.sharedoc.db.UserDB.WebDataCallBack;
import cc.sjfx.sharedoc.db.bmob.User;
import cc.sjfx.sharedoc.function.AsyncImageLoader;
import cc.sjfx.sharedoc.function.AsyncImageLoader.ImageCallback;
import cc.sjfx.sharedoc.services.DownloadService;
import cc.sjfx.sharedoc.utils.CheckUtils;
import cc.sjfx.sharedoc.utils.CacheUtil;
import cc.sjfx.sharedoc.widget.view.ButtonWithNumber;
import cc.sjfx.sharedoc.widget.view.ListViewForScrollView;
import cc.sjfx.sharedoc.widget.view.xlistview.XListView;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ExamXListViewAdapter extends BaseAdapter {
	private Context context;
	private List<ExamShowListViewBean> list = new ArrayList<ExamShowListViewBean>();
	private XListView xlistView;
	ViewHolder holder = null;
	AsyncImageLoader loader;
	View view = null;

	public ExamXListViewAdapter(Context context,
			List<ExamShowListViewBean> list, XListView xListView) {
		this.context = context;
		this.list = list;
		this.xlistView = xListView;
		loader = new AsyncImageLoader(context);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	private class ViewHolder {
		public TextView nickText;
		public TextView titleText;
		public TextView contenText;
		public TextView downloadUrlText;
		public RelativeLayout downloadLayout;
		public ImageView starImg;
		public ButtonWithNumber buttonWithNumber;
		public ImageView userIcoImg;
		public ListViewForScrollView fileListView;
		public TextView createTimeText;
		public TextView publisherText;
		public TextView publishTimeText;
		public FileAdapter adapter;
		public boolean isCollected = false;
	}

	@Override
	public View getView(final int arg0, View arg1, ViewGroup arg2) {
		// TODO Auto-generated method stub
		holder = null;
		final ExamShowListViewBean bean = list.get(arg0);
		if (arg1 == null) {
			holder = new ViewHolder();
			arg1 = LayoutInflater.from(context).inflate(
					R.layout.xlistview_exam, null);
			view = arg1;
			holder.buttonWithNumber = (ButtonWithNumber) view
					.findViewById(R.id.button2);
			holder.contenText = (TextView) view.findViewById(R.id.contentText);
			holder.nickText = (TextView) view.findViewById(R.id.nickText);
			holder.starImg = (ImageView) view.findViewById(R.id.starImg1);
			holder.downloadLayout = (RelativeLayout) view
					.findViewById(R.id.downloadLayout);
			holder.downloadUrlText = (TextView) view
					.findViewById(R.id.downloadUrlText);
			if (holder.isCollected) {
				holder.starImg.setImageResource(R.drawable.star_collected);
			}
			holder.titleText = (TextView) view.findViewById(R.id.titleText);
			holder.userIcoImg = (ImageView) view.findViewById(R.id.icoImg);
			holder.fileListView = (ListViewForScrollView) view
					.findViewById(R.id.fileListView);
			holder.createTimeText = (TextView) view
					.findViewById(R.id.createTimeText);
			holder.publisherText = (TextView) view
					.findViewById(R.id.publishText);
			holder.publishTimeText = (TextView) view
					.findViewById(R.id.publishTimeText);
			view.setTag(holder);

		} else {
			holder = (ViewHolder) arg1.getTag();
		}
		if (!UserCache.isLogin || UserCache.user.getCollectList() == null) {
			holder.isCollected = false;
		} else {
			holder.isCollected = UserCache.user.getCollectList().contains(
					bean.getObjectId());
		}

		holder.buttonWithNumber.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

			}
		});
		arg1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Bundle bundle = new Bundle();
				bundle.putSerializable("info", bean);
				bundle.putInt("type", 1);
				((BasicFragmentActivity) context).startActivity(bundle,
						DetailActivity.class);
			}
		});
		holder.titleText.setText(bean.getTitle());
//		if (CheckUtils.stringIsNull(bean.getUser().ico)) {
//			UserDB.getUserData(context, bean.getUser().username,
//					new WebDataCallBack() {
//
//						@Override
//						public void getIco(String img) {
//							// TODO Auto-generated method stub
//							loader.loadDrawable(img, new ImageCallback() {
//								@Override
//								public void imageLoaded(Bitmap bitmap) {
//									holder.userIcoImg.setImageBitmap(bitmap);
//									notifyDataSetChanged();
//								}
//							});
//						}
//					});
//		} else {
//			loader.loadDrawable(bean.getUser().ico, new ImageCallback() {
//				@Override
//				public void imageLoaded(Bitmap bitmap) {
//					holder.userIcoImg.setImageBitmap(bitmap);
//				}
//			});
//		}
		loader.loadDrawable(bean.getUser().ico, new ImageCallback() {
			@Override
			public void imageLoaded(Bitmap bitmap) {
				holder.userIcoImg.setImageBitmap(bitmap);
			}
		});
		holder.contenText.setText(bean.getContent());
		if (CheckUtils.isWebSite(bean.getDownloadUrl())
				&& !bean.getDownloadUrl().equals("http://")) {
			holder.downloadLayout.setVisibility(View.VISIBLE);
			holder.downloadUrlText.setText(Html.fromHtml("<a href='"
					+ bean.getDownloadUrl() + "'><i>" + bean.getDownloadUrl()
					+ "</i></a>"));
			holder.downloadUrlText.setMovementMethod(LinkMovementMethod
					.getInstance());
		} else {
			holder.downloadLayout.setVisibility(View.GONE);
		}
		holder.nickText.setText(bean.getUser().nickName);
		holder.buttonWithNumber.setCount(bean.getReplyNum());
		initFileList(bean.getFile());
		holder.createTimeText.setText(bean.getCreateTime());
		holder.publisherText.setText(bean.getPublisher());
		holder.publishTimeText.setText(bean.getPublishTime());
		holder.fileListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new Builder(context);
				try {
					JSONArray jsonArray = new JSONArray(bean.getFile());
					final String fileNetName = jsonArray.getJSONObject(arg2)
							.getString("fileNetName");
					final String fileName = jsonArray.getJSONObject(arg2)
							.getString("fileName");
					builder.setTitle("是否下载该文件")
							.setPositiveButton("下载",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											if (UserCache.isLogin) {
												// doDownload(fileNetName);
												Map<String, String> map = new HashMap<String, String>();
												map.put("fileName", fileName);
												map.put("fileNetName",
														fileNetName);
												if (CacheUtil.taskList == null
														|| CacheUtil.taskList
																.isEmpty()) {
													CacheUtil.taskList = new ArrayList<Map<String, String>>();
													CacheUtil.taskList.add(map);
													Intent intent = new Intent(
															"startDownload");
													context.sendBroadcast(intent);
													doDownload();
												} else {
													MToast.show(context,
															"已添加到下载列表");
													CacheUtil.taskList.add(map);
												}
											} else {
												((BasicFragmentActivity) context)
														.startActivity(
																null,
																UserLoginActivity.class);
											}
										}
									}).setNegativeButton("返回", null).show();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		holder.nickText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				MLog.i("clickNick");
			}
		});
		if (holder.isCollected) {
			holder.starImg.setImageResource(R.drawable.star_collected);
		} else {
			holder.starImg.setImageResource(R.drawable.star);
		}
		holder.starImg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (UserCache.isLogin) {
					boolean iscollect = UserCache.user.getCollectList()
							.contains(bean.getObjectId());
					doCollection(bean.getObjectId(), holder.starImg, iscollect);
				} else {
					((BasicFragmentActivity) context).startActivity(null,
							UserLoginActivity.class);
				}
			}
		});
		return arg1;
	}

	private void initFileList(final String file) {
		// TODO Auto-generated method stub
		ThreadUtils.executorService.execute(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Message msg = new Message();
				msg.what = 1;
				msg.obj = file;
				handler.sendMessage(msg);
			}
		});

	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				String file = (String) msg.obj;
				holder.adapter = new FileAdapter(context, file);
				holder.fileListView.setAdapter(holder.adapter);
				break;

			default:
				break;
			}
		}
	};

	protected void doCollection(String objectId, final ImageView starImg,
			final boolean isCollected) {
		// TODO Auto-generated method stub
		List<String> list = UserCache.user.getCollectList();
		if (isCollected) {
			list.remove(objectId);
		} else {
			list.add(objectId);
		}
		User user = new User();
		user.setCollectList(list);
		user.update(context, UserCache.user.getObjectId(),
				new UpdateListener() {
					@Override
					public void onSuccess() {
						// TODO Auto-generated method stub
						if (isCollected) {

							MToast.show(context, "已取消");
							starImg.setImageResource(R.drawable.star);
						} else {
							MToast.show(context, "已收藏");
							starImg.setImageResource(R.drawable.star_collected);
						}
						notifyDataSetChanged();
					}

					@Override
					public void onFailure(int arg0, String arg1) {
						// TODO Auto-generated method stub
						MToast.show(context, "收藏失败，请稍后再试");
					}
				});
	}

	private void doDownload() {
		// TODO Auto-generated method stub
		MToast.show(context, "已添加到下载列表");
		Intent intent = new Intent(context, DownloadService.class);
		context.startService(intent);
	}

}
